﻿using EventYard.Data;
using EventYard.Models;
using EventYard.Services.Attributes;
using EventYard.Services.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http.ValueProviders;
using System.Web.Mvc;

namespace EventYard.Services.Controllers
{
    public class EventsController : BaseApiController
    {
        [ActionName("getEvents")]
        public HttpResponseMessage GetEvents([ValueProvider(typeof(HeaderValueProviderFactory<string>))] string sessionKey)
        {
            var responseMsg = this.PerformOperationAndHandleExceptions(
                () =>
                {
                    var context = new EventContext();
                    var creator = context.Users.First(u => u.SessionKey == sessionKey);
                    var events = context.Events.Where(e => e.CreatorId == creator.Id);
                    var eventModel = from e in events
                                        select new EventModel
                                        {
                                            Id = e.Id,
                                            Notes = e.Notes,
                                            Place = e.Place,
                                            Time = e.Time,
                                            Title = e.Title,
                                            NotRegistredUsers = (from u in e.NotRegistredUsers
                                                                 select u.Name),
                                            RegistredUsers = (from ru in e.RegistredUsers
                                                              select new EventUserModel
                                                              {
                                                                  Id = ru.Id,
                                                                  Username = ru.Username
                                                              })
                                        };

                    var response =
                        this.Request.CreateResponse(HttpStatusCode.OK, eventModel);
                    return response;
                });

            return responseMsg;
        }

        [HttpPost]
        [ActionName("createEvent")]
        public HttpResponseMessage CreateEvent([ValueProvider(typeof(HeaderValueProviderFactory<string>))] string sessionKey, EventModel eventModel)
        {
            var responseMsg = this.PerformOperationAndHandleExceptions(
                () =>
                {
                    var context = new EventContext();
                    using (context)
                    {
                        var user = context.Users.FirstOrDefault(u => u.SessionKey == sessionKey);

                        var newEvent = new Event
                        {
                            CreatorId = user.Id,
                            Place = eventModel.Place,
                            Title = eventModel.Title,
                            Time = eventModel.Time,
                            Notes = eventModel.Notes
                        };

                        context.Events.Add(newEvent);

                        EventUsername notRegistredUser;
                        foreach (var nUser in eventModel.NotRegistredUsers)
	                    {
                            notRegistredUser = context.EventUsernames.FirstOrDefault(u => u.Name == nUser);
                            if (notRegistredUser == null)
                            {
                                notRegistredUser = new EventUsername
                                {
                                    Name = nUser
                                };
                                context.EventUsernames.Add(notRegistredUser);
                            }

                            notRegistredUser.Events.Add(newEvent);
	                    }

                        User registredUser;
                        foreach (var rUser in eventModel.RegistredUsers)
                        {
                            registredUser = context.Users.FirstOrDefault(u => u.Id == rUser.Id);
                            if (registredUser == null)
	                        {
                                throw new ArgumentException("User does NOT exist!");
	                        }

                            registredUser.Events.Add(newEvent);
                        }

                        context.SaveChanges();

                        var response =
                            this.Request.CreateResponse(HttpStatusCode.Created, eventModel);
                        return response;
                    }
                });

            return responseMsg;
        }
    }
}
